package com.ruoyi.web.controller.system;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CommunityPost;
import com.ruoyi.system.domain.CommunityComment;
import com.ruoyi.system.domain.CommunityLike;
import com.ruoyi.system.service.ICommunityService;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 社区管理Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/community")
public class CommunityController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommunityController.class);

    @Autowired
    private ICommunityService communityService;

    /**
     * 获取帖子列表
     */
    @GetMapping("/posts")
    public TableDataInfo list(CommunityPost post) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        post.setUserId(userId);
        List<CommunityPost> list = communityService.selectPostList(post);
        return getDataTable(list);
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/posts/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId) {
        Long userId = SecurityUtils.getUserId();
        CommunityPost post = communityService.selectPostById(postId);
        return success(post);
    }

    /**
     * 发布帖子
     */
    @Log(title = "社区管理", businessType = BusinessType.INSERT)
    @PostMapping("/posts")
    public AjaxResult add(@RequestBody CommunityPost post) {
        post.setUserId(SecurityUtils.getUserId());
        return toAjax(communityService.insertPost(post));
    }

    /**
     * 修改帖子
     */
    @Log(title = "社区管理", businessType = BusinessType.UPDATE)
    @PutMapping("/posts")
    public AjaxResult edit(@RequestBody CommunityPost post) {
        return toAjax(communityService.updatePost(post));
    }

    /**
     * 删除帖子
     */
    @Log(title = "社区管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/posts/{postIds}")
    public AjaxResult remove(@PathVariable Long[] postIds) {
        return toAjax(communityService.deletePostByIds(postIds));
    }

    /**
     * 获取用户点赞过的帖子列表
     */
    @GetMapping("/posts/liked")
    public TableDataInfo listLikedPosts(CommunityPost post) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<CommunityPost> list = communityService.selectLikedPostList(userId, post);
        return getDataTable(list);
    }

    /**
     * 获取评论列表
     */
    @GetMapping("/posts/{postId}/comments")
    public TableDataInfo listComments(@PathVariable Long postId, CommunityComment comment) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        comment.setPostId(postId);
        comment.setUserId(userId);
        comment.setStatus("0");
        List<CommunityComment> comments = communityService.selectCommentList(postId, userId);
        
        // 获取评论总数（包括回复）
        int totalComments = 0;
        for (CommunityComment c : comments) {
            totalComments++; // 计算主评论
            if (c.getReplies() != null) {
                totalComments += countAllReplies(c.getReplies()); // 递归计算所有回复
            }
        }
        
        TableDataInfo rspData = getDataTable(comments);
        rspData.setTotal(totalComments); // 设置正确的总评论数
        return rspData;
    }

    // 递归计算所有回复的数量
    private int countAllReplies(List<CommunityComment> replies) {
        int count = replies.size();
        for (CommunityComment reply : replies) {
            if (reply.getReplies() != null && !reply.getReplies().isEmpty()) {
                count += countAllReplies(reply.getReplies());
            }
        }
        return count;
    }

    /**
     * 获取用户评论过的帖子列表
     */
    @GetMapping("/posts/commented")
    public TableDataInfo listCommentedPosts(CommunityPost post) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<CommunityPost> list = communityService.selectCommentedPostList(userId, post);
        return getDataTable(list);
    }

    /**
     * 发表评论
     */
    @Log(title = "社区管理", businessType = BusinessType.INSERT)
    @PostMapping("/comments")
    public AjaxResult addComment(@RequestBody CommunityComment comment) {
        comment.setUserId(SecurityUtils.getUserId());
        return toAjax(communityService.insertComment(comment));
    }

    /**
     * 点赞
     */
    @Log(title = "社区管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{type}/{id}/like")
    public AjaxResult like(@PathVariable String type, @PathVariable Long id) {
        // 直接返回 service 层的结果，1表示点赞，0表示取消点赞
        int result = communityService.like(type, id);
        return AjaxResult.success(result);
    }

    // 辅助方法：构建评论的树形结构
    private List<CommunityComment> buildCommentTree(List<CommunityComment> comments) {
        List<CommunityComment> topLevelComments = new java.util.ArrayList<>();
        java.util.Map<Long, CommunityComment> commentMap = new java.util.HashMap<>();

        // 将所有评论放入Map，方便查找
        for (CommunityComment comment : comments) {
            commentMap.put(comment.getCommentId(), comment);
            // 初始化children列表，避免空指针
            comment.setReplies(new java.util.ArrayList<>());
        }

        // 构建父子关系
        for (CommunityComment comment : comments) {
            // 如果有父评论且父评论存在于Map中，则将其添加到父评论的replies列表中
            if (comment.getParentId() != null && comment.getParentId() != 0 && commentMap.containsKey(comment.getParentId())) {
                commentMap.get(comment.getParentId()).getReplies().add(comment);
            } else {
                // 否则，认为是顶层评论
                topLevelComments.add(comment);
            }
        }
        return topLevelComments;
    }

    /**
     * 获取评论详情
     */
    @GetMapping("/comments/{commentId}")
    public AjaxResult getCommentInfo(@PathVariable Long commentId) {
        return success(communityService.selectCommentById(commentId));
    }

    /**
     * 修改评论
     */
    @Log(title = "社区管理", businessType = BusinessType.UPDATE)
    @PutMapping("/comments")
    public AjaxResult editComment(@RequestBody CommunityComment comment) {
        return toAjax(communityService.updateComment(comment));
    }

    /**
     * 删除评论
     */
    @Log(title = "社区管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/comments/{commentIds}")
    public AjaxResult removeComment(@PathVariable Long[] commentIds) {
        return toAjax(communityService.deleteCommentByIds(commentIds));
    }

    /**
     * 获取用户点赞列表
     */
    @GetMapping("/likes")
    public TableDataInfo listLikes(CommunityLike like) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        like.setUserId(userId);
        List<CommunityLike> list = communityService.selectLikeList(like);
        return getDataTable(list);
    }

    /**
     * 检查用户是否点赞
     */
    @GetMapping("/check-like/{type}/{id}")
    public AjaxResult checkLike(@PathVariable String type, @PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        CommunityLike like = communityService.selectLikeByUserAndTarget(userId, id, type);
        return success(like != null);
    }

    /**
     * 获取所有评论列表
     */
    @GetMapping("/comments")
    public TableDataInfo listAllComments(CommunityComment comment) {
        startPage();
        List<CommunityComment> list = communityService.selectAllCommentList(comment);
        return getDataTable(list);
    }
} 